<template>
  <el-autocomplete
    v-model="form[item.key]"
    :style="style"
    :placeholder="placeholder"
    :fetch-suggestions="querySearch"
    :disabled="itemDisabled"
    :value-key="item.key"
    clearable
    @select="handleSelect"
    @blur="handleSelect"
  />
</template>

<script lang="ts">
import { defineComponent, PropType, toRefs } from 'vue'
import { Autocomplete, FormItem, Options } from '../types'
import { ObjectType } from 'typings/interfaces'
import usePlacehoder from '@/hooks/usePlacehoder'
import useDisabled from '../hooks/useDisabled'
import { get, find, forEach } from 'lodash'

export default defineComponent({
  emits: {
    'update:form': null,
  },
  props: {
    item: {
      type: Object as PropType<Autocomplete>,
      required: true,
    },
    form: {
      type: Object as PropType<Record<string, string>>,
      required: true,
    },
    placeholderId: {
      type: String,
      default: () => '',
    },
    disabled: {
      type: Boolean,
      required: true,
    },
    autocompleteOptions: {
      type: Object as PropType<ObjectType>,
      default: () => ({}),
    },
  },
  setup(props) {
    const placeholder = usePlacehoder(props.item, 'lang.placeholder.inputOrSelect')
    const itemDisabled = useDisabled(props.disabled, props.item.disabled)
    const key = get(props, 'item.alias') ?? get(props, 'item.key', '')

    const querySearch = (queryString: string, cb: any) => {
      const results = queryString
        ? props.autocompleteOptions[props.item.key].filter(createFilter(queryString))
        : props.autocompleteOptions[props.item.key]
      // call callback function to return suggestions
      cb(results)
    }

    const handleSelect = () => {
      const row = find(props.autocompleteOptions[props.item.key], {
        [key]: props.form[props.item.key],
      })
      row &&
        forEach(props.item.shouldUpdate, ([key, alias]) => {
          props.form[key] = get(row, alias ?? key)
        })
    }

    const createFilter = (queryString: string) => {
      return (item) => {
        return item[props.item.key].indexOf(queryString) > -1
      }
    }

    return {
      style: {
        width: props.item?.width ? props.item.width + 'px' : '100%',
      },
      itemDisabled,
      placeholder,
      querySearch,
      handleSelect,
    }
  },
})
</script>
